//
//  RegisterViewController.m
//  wanhucang
//
//  Created by 郝志宇 on 16/1/27.
//  Copyright © 2016年 XuDong Jin. All rights reserved.
//

#import "RegisterViewController.h"
#import "RegisterTwoViewController.h"
#import "IGRegisterApi.h"
#import "userEditViewController.h"
#import "AppDelegate.h"
#import "IGCommonApi.h"
#import "IGWebViewController.h"
#import "IGPwdTextField.h"
#import "IGCaptchaView.h"

@interface RegisterViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSString *phonenum;
    NSString *vertifynum;
    NSString *passwordone;
    NSString *passwordtwo;
    UIButton *verBtn;
    
    BOOL isSel;
    NSInteger timer;
}

@property (nonatomic, strong) IGRegisterApi *registerApi;
@property (nonatomic, strong) IGCommonApi *commonApi;

@end


@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = NSLocalizedString(@"Mobile Registration", nil);

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidTakeScreenshot) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    
    __weak typeof(self) weakSelf = self;
    [self.view setTapActionWithBlock:^{
        [weakSelf.view endEditing:YES];
    }];
    
    isSel = YES;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, GSCALE(150))];
//    view.backgroundColor = [UIColor greenColor];
    
    UIButton *sel = [UIButton buttonWithType:UIButtonTypeCustom];
    sel.frame = CGRectMake(0, 30, 25, 25);
    [sel setImage:[UIImage imageNamed:@"未标题-1-2"] forState:UIControlStateSelected];
    [sel setImage:[UIImage imageNamed:@"未标题-1-1"] forState:UIControlStateNormal];
    [sel addTarget:self action:@selector(selProtocol:) forControlEvents:UIControlEventTouchUpInside];
    sel.selected = isSel;
    [view addSubview:sel];
    
    UILabel *read = [[UILabel alloc] initWithFrame:CGRectZero];
    read.font = [UIFont font12];
    read.text = NSLocalizedString(@"I have read and agreed", nil);
    read.textColor = [UIColor c5Color];
    [read sizeToFit];
    read.centerY=sel.centerY;
    [view addSubview:read];
    
    UILabel *protocol = [[UILabel alloc] initWithFrame:CGRectZero];
    protocol.font = [UIFont font12];
    protocol.userInteractionEnabled = YES;
    protocol.text = [NSString stringWithFormat:@"《%@》",NSLocalizedString(@"Registration Agreement",nil)];
    [protocol sizeToFit];
    protocol.bottom = read.bottom;
    NSMutableAttributedString *lineText = [[NSMutableAttributedString alloc] initWithString:protocol.text];
    [lineText addAttribute:NSForegroundColorAttributeName value:[UIColor c1Color] range:NSMakeRange(0, lineText.length)];
    protocol.attributedText = lineText;
    [view addSubview:protocol];
    [protocol setTapActionWithBlock:^{
        IGWebViewController *vc = [[IGWebViewController alloc] initWithType:IGWebViewTypeThree];
        [UIViewController ig_pushViewController:vc animated:YES];
    }];
    
    UIButton *submit = [UIButton buttonWithType:UIButtonTypeCustom];
    submit.backgroundColor = [UIColor appColor];
    submit.layer.cornerRadius = 20.f;
    submit.layer.masksToBounds = YES;
    submit.frame = CGRectMake(0, 0, GSCALE(300), GSCALE(44));
    submit.titleLabel.font = [UIFont font16];
    [submit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [submit setTitle:NSLocalizedString(@"Register Now", nil) forState:UIControlStateNormal];
    [submit addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
    submit.center = CGPointMake(view.width/2, submit.height/2);
    submit.y = read.bottom + 15;
    
    sel.x = submit.x+5;
    read.left = sel.right+5;
    protocol.left = read.right;
    [view addSubview:submit];
    
    self.table.tableFooterView = view;
    
    self.table.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
    self.table.backgroundColor =[UIColor c2Color];
}

#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    CGFloat x = cell.separatorInset.left;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UITextField *textView = [[UITextField alloc] initWithFrame:CGRectMake(x, 0, KSCREENWIDTH-2*x, 50)];
    if (indexPath.row==0) {
        textView.text = phonenum;
        textView.keyboardType = UIKeyboardTypeNumberPad;
        UILabel *left = [[UILabel alloc] initWithFrame:CGRectZero];
        left.text = NSLocalizedString(@"Mobile Number", nil);
        left.textColor=[UIColor c4Color];
        left.font = [UIFont font16];
        [left sizeToFit];
        left.width += 20;
        textView.leftView = left;
        
        UILabel *right = [[UILabel alloc] initWithFrame:CGRectZero];
        right.text = NSLocalizedString(@"Mobile Number", nil);
        right.textColor=[UIColor c5Color];
        right.textAlignment=NSTextAlignmentRight;
        right.font = [UIFont font16];
        [right sizeToFit];
        right.width += 20;
        textView.rightView = right;
        [cell.contentView addSubview:textView];
    }else if (indexPath.row==1) {
        textView.size=CGSizeMake(KSCREENWIDTH-2*x-96, 50);
        textView.text = vertifynum;
        textView.keyboardType = UIKeyboardTypeNumberPad;
        UILabel *left = [[UILabel alloc] initWithFrame:CGRectZero];
        left.text = NSLocalizedString(@"Verification Code", nil);
        left.font = [UIFont font16];
        [left sizeToFit];
        left.width +=20;
        textView.leftView = left;
        
        UILabel *right = [[UILabel alloc] initWithFrame:CGRectZero];
        right.text = NSLocalizedString(@"SMS Code", nil);
        right.textColor=[UIColor c5Color];
        right.textAlignment=NSTextAlignmentRight;
        right.font = [UIFont font16];
        [right sizeToFit];
        right.width += 20;
        textView.rightView = right;
        [cell.contentView addSubview:textView];
        
        UIButton *identyBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        [identyBtn setTitle:NSLocalizedString(@"Acquire", nil) forState:UIControlStateNormal];
        [identyBtn setTitleColor:[UIColor c5Color] forState:UIControlStateDisabled];
        [identyBtn setTitleColor:[UIColor c1Color] forState:UIControlStateNormal];
        [identyBtn addTarget:self action:@selector(getCode) forControlEvents:UIControlEventTouchUpInside];
        identyBtn.enabled = YES;
        identyBtn.titleLabel.font=[UIFont font16];
        [identyBtn sizeToFit];
        identyBtn.centerY=textView.centerY;
        identyBtn.x=KSCREENWIDTH-x-identyBtn.width;
        verBtn=identyBtn;
        [cell.contentView addSubview:identyBtn];
        
        
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, KSCREENWIDTH, .5)];
        line.backgroundColor = [UIColor c6Color];
        [cell.contentView addSubview:line];
    }else if (indexPath.row==2){
        textView = [[IGPwdTextField alloc] initWithFrame:CGRectMake(x, 0, KSCREENWIDTH-2*x, 50)];
        textView.text = passwordone;
        textView.keyboardType = UIKeyboardTypeAlphabet;
        textView.secureTextEntry = YES;
        UILabel *left = [[UILabel alloc] initWithFrame:CGRectZero];
        left.text = NSLocalizedString(@"Password", nil);
        left.font = [UIFont font16];
        [left sizeToFit];
        left.width += 35;
        textView.leftView = left;
        
        UILabel *right = [[UILabel alloc] initWithFrame:CGRectZero];
        right.text = NSLocalizedString(@"6-16 Digits or Characters", nil);
        right.textColor=[UIColor c5Color];
        right.textAlignment=NSTextAlignmentRight;
        right.font = [UIFont font16];
        [right sizeToFit];
        right.width += 20;
        textView.rightView = right;
        
        [cell.contentView addSubview:textView];
        
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, KSCREENWIDTH, .5)];
        line.backgroundColor = [UIColor c6Color];
        [cell.contentView addSubview:line];
    }else if (indexPath.row==3){
        textView = [[IGPwdTextField alloc] initWithFrame:CGRectMake(x, 0, KSCREENWIDTH-2*x, 50)];
        textView.text = passwordtwo;
        textView.keyboardType = UIKeyboardTypeAlphabet;
        textView.secureTextEntry = YES;
        UILabel *left = [[UILabel alloc] initWithFrame:CGRectZero];
        left.text = NSLocalizedString(@"Confirm Password", nil);
        left.font = [UIFont font16];
        [left sizeToFit];
        left.width += 6;
        textView.leftView = left;
        UILabel *right = [[UILabel alloc] initWithFrame:CGRectZero];
        right.text = NSLocalizedString(@"Password Again", nil);
        right.textColor=[UIColor c5Color];
        right.textAlignment=NSTextAlignmentRight;
        right.font = [UIFont font16];
        [right sizeToFit];
        right.width += 20;
        textView.rightView = right;
        
        [cell.contentView addSubview:textView];
        
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, KSCREENWIDTH, .5)];
        line.backgroundColor = [UIColor c6Color];
        [cell.contentView addSubview:line];
    }
    textView.borderStyle = UITextBorderStyleNone;
    textView.leftViewMode = UITextFieldViewModeAlways;
    textView.rightViewMode=UITextFieldViewModeUnlessEditing;
    textView.font = [UIFont font16];
    textView.clearButtonMode = UITextFieldViewModeWhileEditing;
    [textView addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    [textView addTarget:self action:@selector(textBeainEditing:) forControlEvents:UIControlEventEditingDidBegin];
    [textView addTarget:self action:@selector(textEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
    textView.tag = indexPath.row;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (void)selProtocol:(UIButton *)btn {
    btn.selected = !btn.isSelected;
    isSel = btn.isSelected;
}

- (void)submitAction:(UIButton *)btn {
    [self.view endEditing:YES];
    
    if (phonenum.length==0) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Mobile Number", nil)];
        return;
    } else if (![phonenum isTelephone]) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Correct Mobile No.", nil)];
        return;
    } else {
        if (vertifynum.length==0) {
            [self presentMessageTips:NSLocalizedString(@"Please Input Verification Code", nil)];
            return;
        } else {
            if (passwordone.length==0) {
                [self presentMessageTips:NSLocalizedString(@"Please input password", nil)];
                return;
            } else if (passwordone.length<6||passwordone.length>16) {
                [self presentMessageTips:NSLocalizedString(@"Please Input 6-16 Digits or Characters", nil)];
                return;
            } else {
                if (passwordtwo.length==0){
                    [self presentMessageTips:NSLocalizedString(@"Password cannot be null, please re-enter the password.", nil)];
                    return;
                } else if(![passwordone isEqualToString:passwordtwo]) {
                    [self presentMessageTips:NSLocalizedString(@"Password not match,please confirm", nil)];
                    return;
                } else {
                    if (!isSel) {
                        [self presentMessageTips:NSLocalizedString(@"Please Read and Check Registration Agreement", nil)];
                        return;
                    }
                }
            }
        }
    }
    
    self.registerApi = [[IGRegisterApi alloc] initWithUsername:phonenum password:passwordone smsCode:vertifynum];
    [self.registerApi startWithDecodeClass:[IGRegisterResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGRegisterResp *resp = responseObject;
            IGRegisterModel *model = resp.data;
            IGUserInfo *userInfo = model.userinfo;
            
            [IGUser loginSuccessWithModel:userInfo completion:nil];
            
            [JPUSHService setAlias:userInfo.uid completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            } seq:1];
            
            userEditViewController *editVC = [[userEditViewController alloc] init];
            editVC.firstLogin = YES;
            [UIViewController ig_pushViewController:editVC animated:YES];
        }
    }];
    
}

- (void)textBeainEditing:(UITextField *)textView {
    self.table.bounces = YES;
}

- (void)textEndEditing:(UITextField *)textView {
    self.table.bounces = NO;
    if ([phonenum isTelephone]) {
        verBtn.enabled=YES;
    }
    if(textView.text.length!=0){
        textView.rightViewMode = UITextFieldViewModeNever;
    }else{
        textView.rightViewMode = UITextFieldViewModeUnlessEditing;
    }
}

- (void)textChange:(UITextField *)textView {
    if (textView.tag == 0) {
        //手机号
        if (textView.text.length>11) {
            textView.text = [textView.text substringToIndex:11];
        }
        phonenum = textView.text;
    }
    if (textView.tag == 1) {  //  验证码
        vertifynum = textView.text;
    }
    if (textView.tag == 2) {
        if (textView.text.length>16) {
            textView.text = [textView.text substringToIndex:16];
        }
        passwordone = textView.text;
    }
    if (textView.tag == 3) {
        if (textView.text.length>16) {
            textView.text = [textView.text substringToIndex:16];
        }
        passwordtwo = textView.text;
    }
    
}

- (void)getCode {
    [self.view endEditing:YES];
    if (phonenum.length==0) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Mobile Number", nil)];
        return;
    } else if (![phonenum isTelephone]) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Correct Mobile No.", nil)];
        return;
    }
    __weak typeof(self) weakSelf = self;
    [IGCaptchaView num:phonenum showCaptcha:^(NSString *cap) {
        [weakSelf getRealCode:cap];
    }];
}

- (void)getRealCode:(NSString *)code {
    if (phonenum.length==0) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Mobile Number", nil)];
        return;
    } else if (![phonenum isTelephone]) {
        [self presentMessageTips:NSLocalizedString(@"Please Input Correct Mobile No.", nil)];
        return;
    }
    [self showText:NSLocalizedString(@"Sending...", nil)];
    timer = 60;
    self.commonApi = [[IGCommonApi alloc] init];
    self.commonApi.apiType = IGiGalleryApiTypeMemberGetPhoneSMSNew;
    self.commonApi.phone = phonenum;
    self.commonApi.code = code;
    __weak typeof(self) weakSelf = self;
    [self.commonApi startWithDecodeClass:[IGCommonResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf presentMessageTips:NSLocalizedString(@"Sent Successfully", nil)];
                verBtn.userInteractionEnabled = NO;
                NSString *title = [NSString stringWithFormat:@"%@ sec", @(timer)];
                [verBtn setTitle:title forState:UIControlStateNormal];
                [verBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                
                [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(timerDown:) userInfo:verBtn repeats:YES];
            });
        }
    }];
}

- (void)timerDown:(NSTimer *)time {
    timer--;
    NSString *title = [NSString stringWithFormat:@"%@ sec", @(timer)];

    [verBtn setTitle:title forState:UIControlStateNormal];
    [verBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    if (timer == 0) {
        verBtn.userInteractionEnabled = YES;
        [verBtn setTitle:NSLocalizedString(@"Acquire", nil) forState:UIControlStateNormal];
        [verBtn setTitleColor:[UIColor appColor] forState:UIControlStateNormal];
        [time invalidate];
    }
}

- (void)userDidTakeScreenshot {
    [UIAlertView bk_showAlertViewWithTitle:@"" message:NSLocalizedString(@"You mobile screen is captured.\n Please pay attention to password security.", nil) cancelButtonTitle:NSLocalizedString(@"Confirm",nil) otherButtonTitles:nil handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
